package com.imast.android.bys.ui;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.imast.android.bys.R;
import com.imast.android.bys.task.SoapPrimitiveTaskFragment;
import com.imast.android.bys.ui.SplashActivity.PlaceholderFragment;
import com.imast.android.bys.util.SessionManager;
import com.imast.android.bys.util.SoapClient;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class SplashHelper implements ConnectionCallbacks,
		OnConnectionFailedListener, OnClickListener {

	private static final String TAG = SplashHelper.class.getSimpleName();

	private static final String TAG_TASK_FRAGMENT = "task_fragment";

	private SoapPrimitiveTaskFragment mTaskFragment;

	public static final int RC_SIGN_IN = 0;
	public static final int RC_FB_SIGN_IN = 1;

	// Profile pic image size in pixels
	private static final int PROFILE_PIC_SIZE = 400;
	
	private SessionManager session;

	// Google client to interact with Google API
	private GoogleApiClient mGoogleApiClient;
	private ConnectionResult mConnectionResult;
	private boolean mIntentInProgress;
	private boolean mSignInClicked;
	private ProgressDialog pDialog;

	private PlaceholderFragment fragment;
	private FragmentActivity mActivity;
	private ActionBar actionBar;
	private EditText edtUsuario;
	private EditText edtClave;
	private Button btnLogin;
	private LoginButton btnFacebook;

	private SignInButton btnSignIn;
	private Button btnSignOut, btnRevokeAccess;
	private ImageView imgProfilePic;
	
	private UiLifecycleHelper uiHelper;
	

	public PlaceholderFragment getFragment() {
		return fragment;
	}

	public FragmentActivity getActivity() {
		return mActivity;
	}

	public ActionBar getActionBar() {
		return actionBar;
	}

	public SoapPrimitiveTaskFragment getTaskFragment() {
		return mTaskFragment;
	}

	public void setTaskFragment(SoapPrimitiveTaskFragment mTaskFragment) {
		this.mTaskFragment = mTaskFragment;
	}

	public GoogleApiClient getGoogleApiClient() {
		return mGoogleApiClient;
	}

	public UiLifecycleHelper getUiHelper() {
		return uiHelper;
	}

	public void setUiHelper(UiLifecycleHelper uiHelper) {
		this.uiHelper = uiHelper;
	}

	public SessionManager getSession() {
		return session;
	}

	public EditText getEdtUsuario() {
		return edtUsuario;
	}

	public EditText getEdtClave() {
		return edtClave;
	}

	public Button getBtnLogin() {
		return btnLogin;
	}

	public LoginButton getBtnFacebook() {
		return btnFacebook;
	}

	public boolean isIntentInProgress() {
		return mIntentInProgress;
	}

	public void setIntentInProgress(boolean mIntentInProgress) {
		this.mIntentInProgress = mIntentInProgress;
	}

	public boolean isSignInClicked() {
		return mSignInClicked;
	}

	public void setSignInClicked(boolean mSignInClicked) {
		this.mSignInClicked = mSignInClicked;
	}
	
	public SplashHelper(int s) {
		
	}

	public SplashHelper(PlaceholderFragment fragment,
			FragmentActivity mActivity, View context, UiLifecycleHelper uiHelper) {
		
		this.fragment = fragment;
		this.mActivity = mActivity;
		this.actionBar = ((ActionBarActivity) mActivity).getSupportActionBar();
		this.uiHelper = uiHelper;
		
		this.session = new SessionManager(getActivity().getApplicationContext());
		
		this.edtUsuario = (EditText) context.findViewById(R.id.edtLogin);
		this.edtClave = (EditText) context.findViewById(R.id.edtClave);
		this.btnLogin = (Button) context.findViewById(R.id.btnLogin);
		this.btnFacebook = (LoginButton) context.findViewById(R.id.btnFacebook);
		this.btnSignIn = (SignInButton) context.findViewById(R.id.btn_sign_in);
		this.btnSignOut = (Button) context.findViewById(R.id.btn_sign_out);
		this.btnRevokeAccess = (Button) context.findViewById(R.id.btn_revoke_access);
		
		initConfig();

	}

	private void initConfig() {
		btnLogin.setOnClickListener(this);
		btnSignIn.setOnClickListener(this);
		btnSignOut.setOnClickListener(this);
		btnRevokeAccess.setOnClickListener(this);
		
		mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this).addApi(Plus.API)
				.addScope(Plus.SCOPE_PLUS_LOGIN).build();
		
	}

	private void loginApp() {

		String usuario = getEdtUsuario().getText().toString().trim();
		String clave = getEdtClave().getText().toString().trim();
		
		if (TextUtils.isEmpty(usuario)){
			Toast.makeText(getActivity().getApplicationContext(), R.string.toastUsuarioEmpty, Toast.LENGTH_SHORT).show();
			return;
		} else if (TextUtils.isEmpty(clave)){
			Toast.makeText(getActivity().getApplicationContext(), R.string.toastClaveEmpty, Toast.LENGTH_SHORT).show();
			return;
		}
		
		FragmentManager fm = getActivity().getSupportFragmentManager();
		mTaskFragment = (SoapPrimitiveTaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);

		String methodName = "AutenticacionUsuario";
		String soapAction = "http://tempuri.org/IServiciosByS/AutenticacionUsuario";
		SoapClient soapClient = new SoapClient(methodName, soapAction);
		soapClient.getRequest().addProperty("Usuario", usuario);
		soapClient.getRequest().addProperty("Contrasena", clave);

		mTaskFragment = new SoapPrimitiveTaskFragment();
		mTaskFragment.setTargetFragment(getFragment(), 0);
		fm.beginTransaction().add(mTaskFragment, TAG_TASK_FRAGMENT).commit();
		mTaskFragment.setSoapClient(soapClient);
		
		if (!mTaskFragment.isRunning()){
			mTaskFragment.start();
		}
		

	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (!result.hasResolution()) {
			GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
					getActivity(), 0).show();
			return;
		}

		if (!mIntentInProgress) {
			// Store the ConnectionResult for later usage
			mConnectionResult = result;

			if (mSignInClicked) {
				// The user has already clicked 'sign-in' so we attempt to
				// resolve all
				// errors until the user is signed in, or they cancel.
				resolveSignInError();
			}
		}
	}

	@Override
	public void onConnected(Bundle arg0) {
		mSignInClicked = false;
		
		// Get user's information
		getProfileInformation();
		
		Intent intent = new Intent(getActivity(), MainActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		getActivity().startActivity(intent);
		
	}

	@Override
	public void onConnectionSuspended(int arg0) {
		mGoogleApiClient.connect();
		updateUI(false);
	}

	/**
	 * Updating the UI, showing/hiding buttons and profile layout
	 * */
	private void updateUI(boolean isSignedIn) {
		if (isSignedIn) {
			btnSignIn.setVisibility(View.GONE);
			btnSignOut.setVisibility(View.VISIBLE);
			btnRevokeAccess.setVisibility(View.VISIBLE);
			// llProfileLayout.setVisibility(View.VISIBLE);
		} else {
			btnSignIn.setVisibility(View.VISIBLE);
			btnSignOut.setVisibility(View.GONE);
			btnRevokeAccess.setVisibility(View.GONE);
			// llProfileLayout.setVisibility(View.GONE);
		}
	}

	private void getProfileInformation() {
		try {
			if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
				Person currentPerson = Plus.PeopleApi
						.getCurrentPerson(mGoogleApiClient);
				String gplusId = currentPerson.getId();
				String name = currentPerson.getDisplayName();
				String personPhotoUrl = currentPerson.getImage().getUrl();
				String personGooglePlusProfile = currentPerson.getUrl();
				String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
				
				session.createLoginSession("demo", name, email, SessionManager.GPLUS_LOGIN, null, gplusId);
				
				Log.e(TAG, "Id: " + gplusId + ", Name: " + name + ", plusProfile: "
						+ personGooglePlusProfile + ", email: " + email
						+ ", Image: " + personPhotoUrl);

			} else {
				Toast.makeText(getActivity().getApplicationContext(),
						"Person information is null", Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Sign-in into google
	 * */
	private void signInWithGplus() {
		if (!mGoogleApiClient.isConnecting()) {
			mSignInClicked = true;
			resolveSignInError();
		}
	}

	/**
	 * Sign-out from google
	 * */
	private void signOutFromGplus() {
		if (mGoogleApiClient.isConnected()) {
			Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
			mGoogleApiClient.disconnect();
			mGoogleApiClient.connect();
			updateUI(false);
		}
	}

	/**
	 * Revoking access from google
	 * */
	private void revokeGplusAccess() {
		if (mGoogleApiClient.isConnected()) {
			Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
			Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
					.setResultCallback(new ResultCallback<Status>() {
						public void onResult(Status arg0) {
							Log.e(TAG, "User access revoked!");
							mGoogleApiClient.connect();
							updateUI(false);
						}

					});
		}
	}

	/**
	 * Method to resolve any signin errors
	 * */
	private void resolveSignInError() {
		if (mConnectionResult.hasResolution()) {
			try {
				mIntentInProgress = true;
				mConnectionResult.startResolutionForResult(getActivity(),
						RC_SIGN_IN);
			} catch (SendIntentException e) {
				mIntentInProgress = false;
				mGoogleApiClient.connect();
			}
		}
	}
	
	
	public void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    if (state.isOpened()) {
	        
	    	getSession().createLoginSession("demo", "demo", "demo@live.com", SessionManager.FB_LOGIN, null, null);
	    	Intent intent = new Intent(getActivity(), MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			getFragment().startActivity(intent);
	    	
	    } else if (state.isClosed()) {
	        Log.i(TAG, "Logged out...");
	    }
	}
	
	public void showDialog() {
		pDialog = new ProgressDialog(getActivity());
		pDialog.setMessage("Cargando...");
		pDialog.show();
	}
	
	public void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
	}

	public void onActivityCreated(Fragment fragment) {

		FragmentManager fm = getActivity().getSupportFragmentManager();
		mTaskFragment = (SoapPrimitiveTaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);

		if (mTaskFragment == null) {
			mTaskFragment = new SoapPrimitiveTaskFragment();
			mTaskFragment.setTargetFragment(getFragment(), 0);
			fm.beginTransaction().add(getTaskFragment(), TAG_TASK_FRAGMENT)
					.commit();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:
			loginApp();
			break;
		case R.id.btn_sign_in:
			signInWithGplus();
			break;
		case R.id.btn_sign_out:
			signOutFromGplus();
			break;
		case R.id.btn_revoke_access:
			revokeGplusAccess();
			break;
		case R.id.btnFacebook:
			break;
		}
	}

}
